package com.face.controller;

import com.face.common.Page;
import com.face.common.Result;
import com.face.common.ResultCode;
import com.face.entity.Remark;
import com.face.entity.User;
import com.face.exception.ArgumentException;
import com.face.exception.DatabaseException;
import com.face.exception.NotFoundException;
import com.face.exception.ServiceException;
import com.face.model.UserModel;
import com.face.service.FileUploadService;
import com.face.service.UserService;
import com.face.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private FileUploadService fileUploadService;

	@PostMapping("/add")
	public Result createUser(@RequestBody UserModel userModel) {
		try {
			byte[] imgData= userModel.getFeatureImageData();
	    	
	    	String imagePath =  fileUploadService.uploadImage(imgData);
	        if(imagePath == null || imagePath.equals("")){
	        	return Result.failure(ResultCode.UPLOAD_IMAGE_FAIL);
	        }
	        String userId = userModel.getUserId();
	        String username = userModel.getUsername();
	        String type = userModel.getType();
	        String group = userModel.getGroup();
	        String detail = userModel.getDetail();
	        String shopId = userModel.getShopId();
	        String mobilephone = userModel.getMobilephone();
	        String creator = userModel.getCreator();
	        User user = new User();
			Date date = new Date();
			user.setUserId(userId);
			user.setImgPath(imagePath);
			user.setUsername(username);
			user.setCreateTime(new Timestamp(date.getTime()));
			user.setUpdateTime(new Timestamp(date.getTime()));
			user.setIsDelete(0);
			user.setType(type);
			user.setGroup(group);
			user.setShopId(shopId);
			user.setCreator(creator);
			user.setVisitCount(1);
			if(!StringUtils.isEmpty(mobilephone)){
				user.setMobilephone(mobilephone);
			}
			
			Remark remark = new Remark();
			remark.setCreator(creator);
			remark.setCreateTime(new Timestamp(date.getTime()));
			remark.setUpdateTime(new Timestamp(date.getTime()));
			remark.setDetail(detail);
			userService.saveUser(user,remark);
		} catch(NotFoundException e){
			return Result.failure(ResultCode.UPLOAD_IMAGE_FAIL);
		}catch (DatabaseException e) {
			return Result.failure(ResultCode.CREATE_FAIL);
		}
		return Result.success(ResultCode.CREATED);
	}
	
	@GetMapping("/list")
	public Result list(String shopId,
					   @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
					   @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
					   @RequestParam(value = "start", required = false) String start,
					   @RequestParam(value = "end", required = false) String end,
					   @RequestParam(name = "sort", required = false) String sort,
					   @RequestParam(name = "order", required = false) String order,
					   @RequestParam(name = "username", required = false) String username,
					   @RequestParam(name = "type", required = false) String type,
					   @RequestParam(name = "creator", required = false) String creator){
		Page<User> pageResult;
		try{
			if(shopId ==null){
				return Result.failure(ResultCode.NOT_ENOUGH_PARAMETER);
			}
			if(StringUtils.isEmpty(shopId)){
				return Result.failure(ResultCode.BAD_PARAMETER);
			}
			pageResult =userService.listAll(shopId,page,limit,start,end,sort,order,username, type, creator);
			if(pageResult.getTotal()==0){
				return Result.failure(ResultCode.NO_RECORDS);
			}


		}catch(ArgumentException  e){
			e.printStackTrace();
			return Result.failure(ResultCode.BAD_PARAMETER);
		}catch(ServiceException e){
			return Result.failure(ResultCode.NO_USER_RECORD);
		}
		
		Result<Page> rs = new Result<>(ResultCode.QUERY_SUCCESS);
		rs.setData(pageResult);
		return rs;
	}

	@GetMapping("/count")
	public Result count(String shopId,String start,String end){
		if(shopId==null||shopId.isEmpty()){
			return Result.failure(ResultCode.NOT_ENOUGH_PARAMETER);
		}
		Integer count=userService.count(shopId,start,end);
		Result<Integer> result =new Result<Integer>(ResultCode.QUERY_SUCCESS);
		result.setData(count);
		return result;
		
	}
	
	@PostMapping("/update")
	public Result updateUser(@RequestBody User user){
		Integer id = user.getId();
		if(id==null){
			return Result.failure(ResultCode.BAD_PARAMETER);
		}
		Integer i=userService.updateUser(user);
		if(i<0){
			return Result.failure(ResultCode.UPDATE_USER_FAIL);
		}
		return Result.success(ResultCode.UPDATE_SUCCESS);
	}

	@GetMapping("/get/{userId}")
	public Result findById(@PathVariable String userId) {
        UserWrapper user = null;
        try {
            user = userService.getUserById(userId);
        } catch (ServiceException e) {
            return Result.success();
        }
		return Result.success(user);
	}

	@GetMapping("/group")
	public Result group(String shopId, Integer type) {
		Map<String, List<User>> map = userService.group(shopId, type);
		return Result.success(map);
	}
}

